package org.example.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.ZkConnection;
import org.apache.zookeeper.CreateMode;
import org.example.common.ZKConnectionHelper;
import org.example.handler.PacketHandler;
import org.example.handler.RpcRequestHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class RpcServer {

    @Autowired
    RpcRequestHandler rpcRequestHandler;

    public void start() throws InterruptedException {
        // 1、创建两个线程池对象
        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup work = new NioEventLoopGroup();

        // 2、创建服务端的启动引导对象
        ServerBootstrap serverBootstrap = new ServerBootstrap();

        // 3、配置启动引导对象
        serverBootstrap.group(boss, work)
                // 设置通道为nio
                .channel(NioServerSocketChannel.class)
                // 创建监听channel
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        // 获取管道对象
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new PacketHandler());
                        pipeline.addLast(rpcRequestHandler);

                    }
                });

        int port = 8001;

        // 4、绑定端口
        serverBootstrap.bind(port).sync();

        // 5、启动成功以后，将自己的信息注册到zk的/rpc/server路径下，使用临时节点
        String path = ZKConnectionHelper.serverPath;
        ZkClient zk = new ZkClient(new ZkConnection(ZKConnectionHelper.zkUrl, 500));

        if (!zk.exists(path)) {
            zk.createPersistent(path, true);
        }

        zk.createEphemeral(path + "/127.0.0.1:" + port);

        System.out.println("Server 启动成功");
    }
}
